package com.bonc.ioc.demo.base.page;


import com.bonc.ioc.common.util.ReflectUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.rmi.ServerException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

/**
 * @author fengshuonan
 * @Date 2017年1月22日 下午11:06:41
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class PagePlugin implements Interceptor {
    private static String dialect = "mysql";
    private static String pageSqlId = "selectByPage";
    private final static String MYSQL = "mysql";
    private final static String ORACLE = "oracle";
    private final static String FIND_ALL = "findAll";


    @Override
    public Object intercept(Invocation ivk) throws Throwable {
        HashMap<String, Object> map = null;
        String sql = null;
        if (ivk.getTarget() instanceof RoutingStatementHandler) {
            RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk.getTarget();
            BaseStatementHandler delegate = (BaseStatementHandler) ReflectUtil.getValueByFieldName(statementHandler, "delegate");
            MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getValueByFieldName(delegate, "mappedStatement");

            //拦截需要分页的SQL
            if (mappedStatement.getId().contains(pageSqlId)) {
                BoundSql boundSql = delegate.getBoundSql();
                //分页SQL<select>中parameterType属性对应的实体参数，即Mapper接口中执行分页方法的参数,该参数不得为空
                Object parameterObject = boundSql.getParameterObject();
                if (parameterObject == null) {
                    throw new Exception("分页参数未初始化！");
                } else {
                    Connection connection = (Connection) ivk.getArgs()[0];
                    String orderBy = null;
                    if (parameterObject instanceof HashMap) {
                        map = (HashMap<String, Object>) parameterObject;
                        map.put("pagination", true);
                    }
                    BoundSql boundSql2 = mappedStatement.getBoundSql(parameterObject);
                    String countSql = boundSql2.getSql();
                    int len = countSql.lastIndexOf("ORDER BY");
                    if (len == -1) {
                        len = countSql.lastIndexOf("order by");
                    }
                    if (len > 0) {
                        countSql = countSql.substring(0, len);
                    }
                    PreparedStatement countStmt = connection.prepareStatement(countSql);
                    BoundSql countbs = new BoundSql(mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject);
                    setParameters(countStmt, mappedStatement, countbs, map);
                    ResultSet rs = null;
                    try {
                        rs = countStmt.executeQuery();
                    } catch (Exception e) {
                        throw e;
                    }
                    int count = 0;
                    if (rs.next()) {
                        count = rs.getInt(1);
                    }
                    rs.close();
                    countStmt.close();
                    //参数就是Page实体
                    if (parameterObject instanceof HashMap) {
                        map = (HashMap<String, Object>) parameterObject;
                        map.put("pagination", false);
                        map.put("totalRows", "" + count);
                    }
                    sql = generatePageSql(boundSql.getSql(), map);
                    //将分页sql语句反射回BoundSql.
                    ReflectUtil.setValueByFieldName(boundSql, "sql", sql);
                }
            }
        }
        try {
            return ivk.proceed();
        } catch (Exception e) {
            throw new Exception(e);
        }
    }


    /**
     * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
     *
     * @param ps
     * @param mappedStatement
     * @param boundSql
     * @param parameterObject
     * @throws SQLException
     */
    private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException {
        ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        if (parameterMappings != null) {
            Configuration configuration = mappedStatement.getConfiguration();
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject);
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                if (parameterMapping.getMode() != ParameterMode.OUT) {
                    Object value;
                    String propertyName = parameterMapping.getProperty();
                    PropertyTokenizer prop = new PropertyTokenizer(propertyName);
                    if (parameterObject == null) {
                        value = null;
                    } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                        value = parameterObject;
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        value = boundSql.getAdditionalParameter(propertyName);
                    } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX) && boundSql.hasAdditionalParameter(prop.getName())) {
                        value = boundSql.getAdditionalParameter(prop.getName());
                        if (value != null) {
                            value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
                        }
                    } else {
                        value = metaObject == null ? null : metaObject.getValue(propertyName);
                    }
                    TypeHandler typeHandler = parameterMapping.getTypeHandler();
                    if (typeHandler == null) {
                        throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId());
                    }
                    typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
                }
            }
        }
    }

    /**
     * 根据数据库方言，生成特定的分页sql
     *
     * @param sql
     * @return
     */
    private String generatePageSql(String sql, HashMap<String, Object> map) throws Exception {
        sql += map.get("orderBy") != null ? " ORDER BY " + (String) map.get("orderBy") : "";
        if (map != null && !StringUtils.isEmpty(dialect)) {
            StringBuffer pageSql = new StringBuffer();
            if (MYSQL.equals(dialect)) {
                pageSql.append(sql);
                try {
                    if (map.get(FIND_ALL) != null && (Boolean) map.get(FIND_ALL)) {

                    } else {
                        try {
                            pageSql.append(" limit " + getPageStartIndex(map) + "," + map.get("pageSize"));
                        } catch (Exception e) {
                            throw e;
                        }
                    }
                } catch (Exception e) {
                    throw new Exception(e);
                }

            } else if (ORACLE.equals(dialect)) {

            }
            System.out.println("pageSql = " + pageSql.toString());
            return pageSql.toString();
        } else {
            return sql;
        }
    }

    @Override
    public Object plugin(Object arg0) {
        return Plugin.wrap(arg0, this);
    }

    @Override
    public void setProperties(Properties p) {
        dialect = p.getProperty("dialect");
        if (StringUtils.isEmpty(dialect)) {
            try {
                throw new ServerException("dialect property is not found!");
            } catch (ServerException e) {
                e.printStackTrace();
            }
        }
        pageSqlId = p.getProperty("pageSqlId");
        if (StringUtils.isEmpty(pageSqlId)) {
            try {
                throw new ServerException("pageSqlId property is not found!");
            } catch (ServerException e) {
                e.printStackTrace();
            }
        }
    }

    private Integer getPageStartIndex(HashMap<String, Object> map) {
        Integer pageNumber = Integer.parseInt((String) map.get("pageNumber"));
        Integer pageSize = Integer.parseInt((String) map.get("pageSize"));
        return (pageNumber - 1) * pageSize;
    }


}
